package com.xfatm.util.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectUtils {

    private ReflectUtils(){

    }

    /**
     * 如果一个对象的某个字段为null，则谁知字段值为 new FieldClass，该字段必须有公共无参构造函数，且对象中需要有该对象的getter/setter方法
     * @param o 对象
     * @param fieldName 要填充的字段名
     */
    public static void fullNullField(Object o,String fieldName)throws Exception{
        if(o==null){
            throw new NullPointerException("对象为null");
        }
        Method get=o.getClass().getDeclaredMethod("get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
        Object getObject=get.invoke(o);
        if(getObject==null){
            Method set=getClassMethodByName(o.getClass(),"set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1));
            Class<?>[] fields=set.getParameterTypes();
            if(fields==null||fields.length!=1){
                throw new Exception("setter方法参数不正确");
            }
            Class<?> c=fields[0];
            Constructor m=c.getConstructor();
            set.invoke(o,m.newInstance());
        }
    }

    public static Method getClassMethodByName(Class<?> c,String name) throws NoSuchMethodException{
        for(Method m:c.getDeclaredMethods()){
            if(m.getName().equals(name)){
                return m;
            }
        }
        throw new NoSuchMethodException("未找到方法:"+name);
    }
}
